import { PrismaService } from '@app/prisma';
import { CollectionEntity } from '@app/prisma/entitys/collection.entity';
import { UserEntity } from '@app/prisma/entitys/user.entity';
import { UseGuards } from '@nestjs/common';
import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
import { GqlAuthGuard, GqlCurrentUser } from 'src/auth/auth.guard';

@Resolver()
export class CollectionResolver {
    constructor(
        private readonly prismaService: PrismaService
    ) { }
    @Query(() => [CollectionEntity])
    @UseGuards(GqlAuthGuard)
    getSelfCollect(
        @GqlCurrentUser() user: UserEntity
    ) {
        return this.prismaService.collection.findMany({
            where: {
                userId: user.id
            },
            include: {
                shop: true
            }
        })
    }
    @Query(() => Boolean)
    @UseGuards(GqlAuthGuard)
    async visCollect(
        @Args("id", { type: () => Int }) id: number,
        @GqlCurrentUser() user: UserEntity
    ) {
        return !!await this.prismaService.collection.findUnique({
            where: {
                userId_shopId: {
                    userId: user.id,
                    shopId: id
                }
            }
        })
    }

    @Mutation(() => Boolean)
    @UseGuards(GqlAuthGuard)
    async setCollect(
        @Args("id", { type: () => Int }) id: number,
        @Args("type", { type: () => Int }) type: number,
        @GqlCurrentUser() user: UserEntity
    ) {
        if (type === 1) {
            if (!await this.prismaService.collection.findUnique({
                where: {
                    userId_shopId: {
                        userId: user.id,
                        shopId: id
                    }
                }
            })) await this.prismaService.collection.create({
                data: {
                    userId: user.id,
                    shopId: id
                }
            })
            return true;
        }
        await this.prismaService.collection.delete({
            where: {
                userId_shopId: {
                    userId: user.id,
                    shopId: id
                }
            }
        })
        return false;
    }

}
